import React from "react";
import type { FormProps } from "antd";
import { Button, Checkbox, Form, Input, message } from "antd";
import { ArrowRightOutlined } from "@ant-design/icons";
import { useNavigate, NavLink } from "react-router-dom";
import axios from "axios";
import "./index.css";

type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};

const Index: React.FC = () => {
  const navigate = useNavigate();
  const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
    console.log("Success:", values);
    axios.post("/api/login", values).then((resp) => {
      let { code, msg, token, info, row, user } = resp.data;
      if (code == 200) {
        message.success(msg);
        localStorage.setItem("token", token);
        localStorage.setItem("row", row);
        localStorage.setItem("info", info);
        localStorage.setItem("user", user);
        navigate("/home/home");
      } else {
        message.error(msg);
      }
    });
  };

  return (
    <div className="box">
      <div className="left">
        <h1>Dcat Admin</h1>
        <p>让后台开发更简单</p>

        <p>Welcome back, please login to your account.</p>

        <div>
          <Form
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            autoComplete="off"
          >
            <Form.Item<FieldType>
              label="Username"
              name="username"
              rules={[
                { required: true, message: "Please input your username!" },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item<FieldType>
              label="Password"
              name="password"
              rules={[
                { required: true, message: "Please input your password!" },
              ]}
            >
              <Input.Password />
            </Form.Item>

            <Form.Item<FieldType>
              name="remember"
              valuePropName="checked"
              wrapperCol={{ offset: 8, span: 16 }}
            >
              <Checkbox>Remember me</Checkbox>
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button type="primary" htmlType="submit">
                Login
                <ArrowRightOutlined />
              </Button>
            </Form.Item>
          </Form>
        </div>
        <div className="zc">
          <NavLink to="/sigin">去注册</NavLink>
        </div>
      </div>
      <div className="right"></div>
    </div>
  );
};
export default Index;
